/*
 * @Author: Songjq
 * @Date: 2021-12-04 13:58:47
 * @Desscription:
 */
const koa = require("koa");
const Router = require("koa-router");
const mongoose = require("mongoose");
const bodyParser = require("koa-bodyparser");
const passport = require("koa-passport");
const cors = require("koa2-cors");
const corsConfigs = require("./config/cors");

// 实例化koa
const app = new koa();

// 处理跨域的配置
app.use(cors(corsConfigs));

// koa-bodyparser主要针对请求报文的处理
app.use(bodyParser());

// 配置路由及请求接口
const router = new Router();

// 引入models数据表模块定义
const users = require("./routes/api/users");
const dns = require("./routes/api/dns");
const login = require("./routes/api/login");
const log = require("./routes/api/log");
const dict = require("./routes/api/dict");
const role = require("./routes/api/role");
const menu = require("./routes/api/menu");
const notice = require("./routes/api/notice");
const config = require("./routes/api/config");
const rechargeOrder = require("./routes/api/rechargeOrder");
const sms = require("./routes/api/sms");

// 定义请求接口
router.use("/api/users", users);
router.use("/api/dns", dns);
router.use("/api", login);
router.use("/api/log", log);
router.use("/api/dict", dict);
router.use("/api/role", role);
router.use("/api/menu", menu);
router.use("/api/notice", notice);
router.use("/api/config", config);
router.use("/api/rechargeOrder", rechargeOrder);
router.use("/api/sms", sms);

// 操作日志中间件
const logAsync = require("./middleware/log-async");
app.use(logAsync());

// 打印日志中间件
const Koa_Logger = require("koa-logger");
const logger = Koa_Logger();
app.use(logger);

// passport权限认证 回调到config文件中 passport.js，用于生成token，判断用户是否登录，以及阻断请求的发起
app.use(passport.initialize());
app.use(passport.session());
require("./config/passport")(passport);

// 连接数据库 配置数据库连接地址
const db = require("./config/keys").mongoURI;
mongoose
    .connect(db, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    .then(() => {
        console.log("Mongodb Connectd...");
    })
    .catch((err) => {
        console.log(err);
    });

// 配置路由
app.use(router.routes()).use(router.allowedMethods());

const port = process.env.PORT || 3889;

app.listen(port, () => {
    console.log(`server started on ${port}`);
});